
import { _decorator, Component, Node, find, loader, Prefab, instantiate } from 'cc';
const { ccclass, property } = _decorator;
interface PageActive {
    show: () => {},
    hide: () => {},
}

/**
 * 主界面管理器
 */
@ccclass('UIManager')
export class UIManager extends Component {
    //保存所有打开过得UI界面的Map(字典)
    static _dictPanel = new Map<string, Node>();

    //打开某个窗口
    public static showDialog(name: string, cb?: Function, ...args: any[]) {
        const scriptName = (name.substr(0, 1)).toUpperCase() + name.substr(1);
        //打开过
        if (this._dictPanel.has(name)) {
            const panel = this._dictPanel.get(name)!;
            const parent = find("Canvas");
            panel.setParent(parent);
            const comp = panel.getComponent(scriptName);
            if (comp && (comp as Component & PageActive)['show']) {
                (comp as Component & PageActive)['show'].apply(comp);
            }
            cb && cb();

            return
        }

        //未打开过
        const path = `ui/${name}`;
        loader.loadRes(path, Prefab, (err: any, prefab: Prefab) => {
            if (err) {
                console.warn(err);
                return;
            }
            const panel = instantiate(prefab)!;
            this._dictPanel.set(name, panel);
            const parent = find("Canvas");
            panel.setParent(parent);
            const comp = panel.getComponent(scriptName);
            if (comp && (comp as Component & PageActive)['show']) {
                (comp as Component & PageActive)['show'].apply(comp);
            }
            cb && cb();
        })
    }

    //关闭某个窗口
    public static hideDialog(name: string, cb?: Function) {
        if (this._dictPanel.has(name)) {
            const panel = this._dictPanel.get(name)!;
            const parent = null
            const scriptName = (name.substr(0, 1)).toUpperCase() + name.substr(1);
            const comp = panel.getComponent(scriptName);
            panel.setParent(parent);
            if (comp && (comp as Component & PageActive)['hide']) {
                (comp as Component & PageActive)['hide'].apply(comp);
            }
            cb && cb();
        }
    }

}
